package org.wyf.EveryPoint.crowd.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.wyf.EveryPoint.common.entity.ImageType;
import org.wyf.EveryPoint.common.utils.FebsUtil;
import org.wyf.EveryPoint.common.annotation.ControllerEndpoint;
import org.wyf.EveryPoint.common.controller.BaseController;
import org.wyf.EveryPoint.common.entity.FebsConstant;
import org.wyf.EveryPoint.common.entity.FebsResponse;
import org.wyf.EveryPoint.common.entity.QueryRequest;
import org.wyf.EveryPoint.common.utils.QRCodeUtil;
import org.wyf.EveryPoint.crowd.entity.Order;
import org.wyf.EveryPoint.crowd.entity.Project;
import org.wyf.EveryPoint.crowd.service.IOrderService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wyf.EveryPoint.crowd.service.IProjectService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户订单表 Controller
 *
 * @author wyf
 * @date 2021-04-09 16:56:33
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class OrderController extends BaseController {

    private final IOrderService orderService;
    private final IProjectService projectService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "order")
    public String orderIndex() {
        return FebsUtil.view("order/order");
    }

    @GetMapping("order")
    @ResponseBody
    @RequiresPermissions("order:list")
    public FebsResponse getAllOrders(Order order) {
        return new FebsResponse().success().data(orderService.findOrders(order));
    }

    @GetMapping("order/list")
    @ResponseBody
    @RequiresPermissions("order:list")
    public FebsResponse orderList(QueryRequest request, Order order) {
        Map<String, Object> dataTable = getDataTable(this.orderService.findOrders(request, order));
        return new FebsResponse().success().data(dataTable);
    }

    @ControllerEndpoint(operation = "新增Order", exceptionMessage = "新增Order失败")
    @PostMapping("order")
    @ResponseBody
    @RequiresPermissions("order:add")
    public FebsResponse addOrder(@Valid Order order) {
        this.orderService.createOrder(order);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "删除Order", exceptionMessage = "删除Order失败")
    @GetMapping("order/delete")
    @ResponseBody
    @RequiresPermissions("order:delete")
    public FebsResponse deleteOrder(Order order) {
        this.orderService.deleteOrder(order);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改Order", exceptionMessage = "修改Order失败")
    @PostMapping("order/update")
    @ResponseBody
    @RequiresPermissions("order:update")
    public FebsResponse updateOrder(Order order) {
        this.orderService.updateOrder(order);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改Order", exceptionMessage = "导出Excel失败")
    @PostMapping("order/excel")
    @ResponseBody
    @RequiresPermissions("order:export")
    public void export(QueryRequest queryRequest, Order order, HttpServletResponse response) {
        List<Order> orders = this.orderService.findOrders(queryRequest, order).getRecords();
        ExcelKit.$Export(Order.class, response).downXlsx(orders, false);
    }

    /**
     * 创建订单
     * @param order
     * @return
     */
    @ControllerEndpoint(operation = "创建订单", exceptionMessage = "创建订单失败")
    @PostMapping("/web/order/saveProjectOrderNoProvide")
    @ResponseBody
    public FebsResponse saveProjectOrderNoProvide(Order order) {
        Date now = new Date();
        order.setUid(getCurrentUser().getUserId());
        order.setCreateTime(now);
        // 等待付款
        order.setState(1);
        //生成订单号
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        order.setOrderNum(sdfTime.format(now).replaceAll("[[\\s-:punct:]]", "")+""+RandomUtil.randomNumbers(5));
        order.setTotal(order.getAddedMoney()+order.getSupport());

        orderService.save(order);
        return new FebsResponse().success().data(order);
    }

    @ControllerEndpoint(operation = "支付订单", exceptionMessage = "支付订单失败")
    @GetMapping("/web/order/getOrderPayQrCode")
    @ResponseBody
    public void getOrderPayQrCode(HttpServletResponse response,String orderId) throws IOException {
        QrConfig config = new QrConfig(300, 300);
// 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
// 生成二维码到文件，也可以到流
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            // 生成指定url对应的二维码到文件，宽和高都是300像素
            QrCodeUtil.generate("http://192.168.43.74:8080/web/project_order_pay_after?orderId="+orderId, config, ImageType.PNG, stream);
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    /**
     * 获取订单状态
     * @param orderId
     * @return
     */
    @ControllerEndpoint(operation = "获取订单状态", exceptionMessage = "获取订单状态失败")
    @PostMapping("/web/order/getOrderState")
    @ResponseBody
    public FebsResponse getOrderState(Long orderId) {
        Order order = orderService.getById(orderId);
        long betweenDay = DateUtil.between(order.getCreateTime(), new Date(), DateUnit.MINUTE);
        if (betweenDay > 30){
            order.setState(2);
        }
        orderService.updateOrder(order);
        return new FebsResponse().success().data(order);
    }

    /**
     * 确定支付订单
     * @param orderId
     * @return
     */
    @ControllerEndpoint(operation = "确定支付订单", exceptionMessage = "确定支付订单失败")
    @PostMapping("/web/order/saveOrderSubmit")
    @ResponseBody
    public FebsResponse saveOrderSubmit(String orderId,String type) {

        Order order = orderService.getById(orderId);
        long betweenDay = DateUtil.between(order.getCreateTime(), new Date(), DateUnit.MINUTE);
        if (betweenDay > 30){
            order.setState(2);
        }else{
            if ("1".equals(type)){
                order.setState(3);
                Project project = projectService.selectProjectByOrderId(orderId);
                project.setRaiseGoal(project.getRaiseGoal()+order.getTotal());
                projectService.updateById(project);
            }else{
                order.setState(4);
            }

        }
        orderService.updateOrder(order);
        return new FebsResponse().success().data(order);
    }

    /**
     * 获取当前用户的全部订单信息
     * @return
     */
    @PostMapping("/order/getAllOrderInfo")
    @ResponseBody
    public FebsResponse getOrderInfo() {
//        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("uid",getCurrentUser().getUserId()).last("order by create_time desc");
//        List<Order> list = orderService.list(queryWrapper);

        List<Order> list = orderService.getAllOrderInfo(getCurrentUser().getUserId());
        return new FebsResponse().success().data(list);
    }


    @PostMapping("/order/getOrderInfoByState")
    @ResponseBody
    public FebsResponse getOrderInfoByState(String state) {

        List<Order> list = orderService.getOrderInfoByState(getCurrentUser().getUserId(),state);
        return new FebsResponse().success().data(list);
    }

    @PostMapping("/web/order/deleteOrderInfo")
    @ResponseBody
    public FebsResponse deleteOrderInfo(String oid) {
        orderService.removeById(oid);
        return new FebsResponse().success().message("删除成功");
    }
}
